<template>
  <div class="app-container" :key="`${operationType}-${articleId || 'new'}`">
    <div slot="header" class="clearfix">
      <span class="card-title">{{ title }}</span>
      <div class="card-actions">
        <el-button @click="goBack" icon="el-icon-back">返回</el-button>
      </div>
    </div>

    <el-form ref="form" :model="form" :rules="rules" label-width="100px">
      <el-form-item label="栏目标题" prop="name">
        <el-input v-model="form.name" placeholder="请输入栏目标题" />
      </el-form-item>

      <el-form-item label="栏目内容" prop="content">
        <editor v-model="form.content" :min-height="192" />
      </el-form-item>

      <el-form-item label="封面图片" prop="coverPath">
        <el-upload ref="upload" :file-list="fileList" :before-upload="beforeUpload" :on-change="handleFileChange"
          :auto-upload="false" :on-remove="handleRemove" :limit="1" list-type="picture-card" accept="image/*" action="#"
          :http-request="handleHttpRequest">
          <i class="el-icon-plus"></i>
          <div slot="tip" class="el-upload__tip">请上传封面图片，大小不小于1MB</div>
        </el-upload>
      </el-form-item>
    </el-form>

    <div class="form-footer">
      <el-button type="primary" @click="submitForm">确 定</el-button>
      <el-button @click="goBack">取 消</el-button>
    </div>
  </div>
</template>

<script>
import { listArticle, getArticle, delArticle, addArticle, updateArticle, uploadFile, uploadContentImage } from "@/api/intergrity-recommend";
import ImageUpload from "@/components/ImageUpload";
import Editor from "@/components/Editor";
import imageCompression from "browser-image-compression";

export default {
  name: "IntegrityRecommendForm",
  dicts: [],
  components: {
    ImageUpload,
    Editor
  },
  data() {
    return {
      // 页面标题
      title: "",
      // 操作类型：add, edit
      operationType: "",
      // 文章ID（编辑时使用）
      articleId: null,

      // 表单参数
      form: {},

      // 封面文件列表
      fileList: [],
      // 待上传的封面文件
      uploadFile: null,

      // 表单校验
      rules: {
        name: [
          { required: true, message: "栏目标题不能为空", trigger: "blur" }
        ],
        content: [
          { required: true, message: "栏目内容不能为空", trigger: "blur" }
        ]
      },
      
      // 暂存文件（用于新增时）
      tempCoverFile: null
    };
  },
  created() {
    this.initPage();
  },
  watch: {
    // 监听路由参数变化
    '$route.query': {
      handler(newQuery, oldQuery) {
        // 当路由参数变化时，重新初始化页面
        if (newQuery.operationType !== oldQuery.operationType || newQuery.id !== oldQuery.id) {
          this.initPage();
        }
      },
      deep: true,
      immediate: false
    }
  },
  methods: {
     // 初始化页面
     initPage() {
       // 先清空所有数据状态
       this.reset();
       
       // 获取路由参数
       const { operationType, id } = this.$route.query;
       this.operationType = operationType || 'add';
       this.articleId = id ? parseInt(id) : null;

       // 设置页面标题
       this.setPageTitle();

       // 如果是编辑模式，加载数据
       if (this.operationType === 'edit' && this.articleId) {
         this.loadArticleData();
       }
       
       // 重新初始化表单
       this.$nextTick(() => {
         this.initForm();
       });
     },
     
     // 初始化表单
     initForm() {
       // 清空表单验证状态
       if (this.$refs.form) {
         this.$refs.form.clearValidate();
       }
       
       // 清空文件上传组件的状态
       if (this.$refs.upload) {
         this.$refs.upload.clearFiles();
       }
       
       // 强制重新渲染表单组件
       this.$forceUpdate();
     },

    // 设置页面标题
    setPageTitle() {
      switch (this.operationType) {
        case 'add':
          this.title = '新增诚信推荐';
          break;
        case 'edit':
          this.title = '修改诚信推荐';
          break;
        default:
          this.title = '诚信推荐管理';
      }
    },

    // 加载文章数据
    loadArticleData() {
      getArticle(this.articleId).then(response => {
        this.form = response.data || response;
        // 初始化文件列表
        if (this.form.coverPath) {
          this.fileList = [{
            name: "封面图片",
            url: this.form.coverPath
          }];
        } else {
          this.fileList = [];
          this.uploadFile = null;
        }
      }).catch(error => {
        console.error('获取文章详情失败:', error);
        this.$modal.msgError('获取文章详情失败: ' + (error.message || '未知错误'));
      });
    },

     // 重置表单
     reset() {
       this.form = {
         id: null,
         name: null,
         content: null,
         coverPath: null
       };
       this.fileList = [];
       this.uploadFile = null;
       
       // 清空暂存文件
       this.tempCoverFile = null;
       
       this.resetForm("form");
     },

    // 返回上一页
    goBack() {
      this.$router.go(-1);
    },

    // 提交表单
    async submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.operationType === 'add') {
            this.handleAdd();
          } else if (this.operationType === 'edit') {
            this.handleUpdate();
          }
        }
      });
    },

     // 新增文章
     async handleAdd() {
       try {
         // 先提交表单，获取文章ID
         const response = await addArticle(this.form);
         if (response.code === 200) {
           // 获取新创建的文章ID
           const newArticleId = response.data?.id || response.data?.articleId;
           
           // 如果有暂存的封面图片，现在上传
           if (this.tempCoverFile && newArticleId) {
             try {
               await this.uploadCoverAfterCreate(newArticleId);
             } catch (uploadError) {
               console.warn('封面上传失败，但文章已创建成功:', uploadError);
               this.$message.warning('文章创建成功，但封面上传失败，请稍后手动上传');
             }
           }
           
           this.$modal.msgSuccess("新增成功");
           // 清空表单数据状态
           this.reset();
           this.goBack();
         } else {
           this.$modal.msgError(response.msg || "新增失败");
         }
       } catch (error) {
         console.error('新增文章失败:', error);
         this.$modal.msgError('新增失败: ' + (error.message || '未知错误'));
       }
     },

    // 修改文章
    async handleUpdate() {
      try {
        // 处理文件上传
        await this.handleFileUpload();

        const response = await updateArticle(this.form);
        if (response.code === 200) {
          this.$modal.msgSuccess("修改成功");
          this.goBack();
        } else {
          this.$modal.msgError(response.msg || "修改失败");
        }
      } catch (error) {
        console.error('修改文章失败:', error);
        this.$modal.msgError('修改失败: ' + (error.message || '未知错误'));
      }
    },

    // 处理文件上传
    async handleFileUpload() {
      if (this.uploadFile) {
        try {
          // 压缩图片
          const compressedFile = await this.compressImage(this.uploadFile);

          // 上传文件
          const formData = new FormData();
          formData.append('file', compressedFile);

          const response = await uploadFile(formData);
          if (response.code === 200) {
            this.form.coverPath = response.url;
          } else {
            throw new Error(response.msg || '文件上传失败');
          }
        } catch (error) {
          console.error('文件上传失败:', error);
          throw error;
        }
      }
    },

     // 文件上传前处理
     beforeUpload(file) {
       const isImage = file.type.startsWith('image/');
       if (!isImage) {
         this.$message.error('只能上传图片文件!');
         return false;
       }

       const isLt2M = file.size / 1024 / 1024 < 2;
       if (!isLt2M) {
         this.$message.error('上传图片大小不能超过 2MB!');
         return false;
       }

       // 如果是新增模式，暂存文件
       if (this.operationType === 'add') {
         this.tempCoverFile = file;
         this.$message.info('封面图片已选择，将在文章创建后上传');
       } else {
         this.uploadFile = file;
       }
       return false; // 阻止自动上传
     },

    // 文件变化处理
    handleFileChange(file, fileList) {
      if (fileList.length > 0) {
        this.uploadFile = fileList[fileList.length - 1].raw;
        this.fileList = [fileList[fileList.length - 1]];
      } else {
        this.uploadFile = null;
        this.fileList = [];
      }
    },

    // 文件移除处理
    handleRemove(file, fileList) {
      this.uploadFile = null;
      this.fileList = [];
    },

    // 文件上传请求处理
    handleHttpRequest(options) {
      this.uploadFileToServer(options.file);
    },

    // 上传文件到服务器
    async uploadFileToServer(file) {
      try {
        const compressedFile = await this.compressImage(file);
        const formData = new FormData();
        formData.append('file', compressedFile);

        const response = await uploadFile(formData);
        if (response.code === 200) {
          this.form.coverPath = response.url;
          this.$message.success('文件上传成功');
        } else {
          throw new Error(response.msg || '上传失败');
        }
      } catch (error) {
        console.error('文件上传失败:', error);
        this.$message.error('文件上传失败: ' + error.message);
        throw error;
      }
    },

     // 图片压缩
     async compressImage(file) {
       const options = {
         maxSizeMB: 1,
         maxWidthOrHeight: 1920,
         useWebWorker: true
       };

       try {
         const compressedFile = await imageCompression(file, options);
         return compressedFile;
       } catch (error) {
         console.error('图片压缩失败:', error);
         // 如果压缩失败，返回原文件
         return file;
       }
     },
     
     // 新增后上传封面图片
     async uploadCoverAfterCreate(articleId) {
       if (!this.tempCoverFile) return;
       
       try {
         const compressedFile = await this.compressImage(this.tempCoverFile);
         const formData = new FormData();
         formData.append('file', compressedFile);
         
         const response = await uploadFile(formData);
         if (response.code === 200) {
           // 更新文章的封面路径
           await updateArticle({
             id: articleId,
             coverPath: response.url
           });
           this.$message.success('封面上传成功');
         }
       } catch (error) {
         console.error('新增后封面上传失败:', error);
         throw error;
       }
     }
  }
};
</script>

<style scoped>
.app-container {
  padding: 20px;
}

.box-card {
  margin-bottom: 20px;
}

.card-title {
  font-size: 18px;
  font-weight: bold;
}

.card-actions {
  float: right;
}

.clearfix:after {
  content: "";
  display: table;
  clear: both;
}

.form-footer {
  text-align: center;
  padding: 20px 0;
  border-top: 1px solid #e4e7ed;
  margin-top: 20px;
}
</style>
